#include "responsivefileitem.h"
#include "layoutstatemanager.h"
#include "filestatusiconmanager.h"
#include <QApplication>
#include <QStyle>
#include <QPainter>
#include <QDebug>
#include <QFileInfo>
#include <QTextLayout>
#include <QLinearGradient>
#include <QRadialGradient>
#include <QPainterPath>
#include <QtMath>
#include <QTimer>
#include <QFontMetrics>
#include <QEasingCurve>

using namespace SonyIveDesign;

ResponsiveFileItem::ResponsiveFileItem(const UnifiedFileInfo& fileInfo,
                                     ResponsiveFileListEngine* engine,
                                     QWidget* parent)
    : QWidget(parent)
    , m_fileInfo(fileInfo)
    , m_engine(engine)
    , m_currentMode(SonyIveDesign::DisplayMode::Standard)
    , m_isSelected(false)
    , m_isHovered(false)
    , m_isPressed(false)
    , m_isDragStarted(false)
    , m_animationOpacity(1.0)
    , m_hoverScale(1.0)
    , m_selectionScale(1.0)
    , m_backgroundCacheDirty(true)
    , m_performanceMode(false)
    , m_sizeHintCached(false)
    , m_layoutMetricsCached(false)
{
    setMouseTracking(true);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 初始化动画系统
    initializeAnimations();

    // 初始化视觉效果
    updateDropShadow();

    // 初始化背景缓存计时器
    m_backgroundCacheTimer = new QTimer(this);
    m_backgroundCacheTimer->setSingleShot(true);
    m_backgroundCacheTimer->setInterval(100);
    connect(m_backgroundCacheTimer, &QTimer::timeout,
            this, &ResponsiveFileItem::onBackgroundCacheUpdate);

}

// === 主要接口实现 ===

void ResponsiveFileItem::setFileInfo(const UnifiedFileInfo& fileInfo)
{
    if (m_fileInfo.fileIdentity != fileInfo.fileIdentity) {
        m_fileInfo = fileInfo;
        m_backgroundCacheDirty = true;
        m_sizeHintCached = false;
        m_layoutMetricsCached = false;

        if (!m_backgroundCacheTimer->isActive()) {
            m_backgroundCacheTimer->start();
        }

        update();
    }
}

void ResponsiveFileItem::setDisplayMode(SonyIveDesign::DisplayMode mode)
{
    if (m_currentMode != mode) {
        SonyIveDesign::DisplayMode oldMode = m_currentMode;
        m_currentMode = mode;
        m_layoutMetricsCached = false;
        m_backgroundCacheDirty = true;
        m_sizeHintCached = false;


        animateModeTransition();
        emit displayModeChanged(mode);
    }
}

void ResponsiveFileItem::setSelected(bool selected)
{
    if (m_isSelected != selected) {
        m_isSelected = selected;
        animateSelection(selected);

        if (m_engine) {
            m_engine->animateSelectionEffect(this, selected);
        }

    }
}

void ResponsiveFileItem::setHovered(bool hovered)
{
    if (m_isHovered != hovered) {
        m_isHovered = hovered;
        animateHover(hovered);

        if (m_engine) {
            m_engine->animateHoverEffect(this, hovered);
        }

        if (hovered && shouldUseComplexEffects()) {
            updateDropShadow();
        }
    }
}

void ResponsiveFileItem::setPressed(bool pressed)
{
    if (m_isPressed != pressed) {
        m_isPressed = pressed;
        m_backgroundCacheDirty = true;
        update();
    }
}

void ResponsiveFileItem::setResponsiveEngine(ResponsiveFileListEngine* engine)
{
    if (m_engine != engine) {
        m_engine = engine;

        if (m_engine) {
            // 同步当前显示模式
            SonyIveDesign::DisplayMode currentMode = m_engine->getCurrentDisplayMode();
            if (currentMode != m_currentMode) {
                setDisplayMode(currentMode);
            }
        }

    }
}

// === 动画属性实现 ===

void ResponsiveFileItem::setAnimationOpacity(double opacity)
{
    if (qAbs(m_animationOpacity - opacity) > 0.01) {
        m_animationOpacity = qBound(0.0, opacity, 1.0);
        update();
    }
}

void ResponsiveFileItem::setHoverScale(double scale)
{
    if (qAbs(m_hoverScale - scale) > 0.01) {
        m_hoverScale = qBound(0.8, scale, 1.2);
        update();
    }
}

void ResponsiveFileItem::setSelectionScale(double scale)
{
    if (qAbs(m_selectionScale - scale) > 0.01) {
        m_selectionScale = qBound(0.9, scale, 1.1);
        update();
    }
}

// === QWidget接口实现 ===

QSize ResponsiveFileItem::sizeHint() const
{
    if (!m_sizeHintCached) {
        if (m_engine) {
            m_cachedSizeHint = m_engine->calculateItemSize(m_currentMode);
        } else {
            // 后备计算
            switch (m_currentMode) {
                case SonyIveDesign::DisplayMode::Micro:    m_cachedSizeHint = QSize(140, 32); break;
                case SonyIveDesign::DisplayMode::Compact:  m_cachedSizeHint = QSize(200, 40); break;
                case SonyIveDesign::DisplayMode::Standard: m_cachedSizeHint = QSize(280, 48); break;
                case SonyIveDesign::DisplayMode::Expanded: m_cachedSizeHint = QSize(380, 56); break;
                case SonyIveDesign::DisplayMode::Full:     m_cachedSizeHint = QSize(480, 64); break;
            }
        }
        m_sizeHintCached = true;
    }

    return m_cachedSizeHint;
}

QSize ResponsiveFileItem::minimumSizeHint() const
{
    return QSize(120, 28); // Micro模式的最小尺寸
}

void ResponsiveFileItem::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);

    // Sony风格分层绘制
    drawSonyBackground(painter);
    drawAdaptiveIcon(painter);
    drawAdaptiveText(painter);

    // 根据显示模式绘制额外元素
    if (m_currentMode >= SonyIveDesign::DisplayMode::Standard) {
        drawProgressIndicator(painter);
    }

    if (m_currentMode >= SonyIveDesign::DisplayMode::Compact) {
        drawStatusBadge(painter);
    }

    // Micro模式的特殊覆盖层
    if (m_currentMode == SonyIveDesign::DisplayMode::Micro) {
        drawMicroOverlay(painter);
    }
}

void ResponsiveFileItem::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);
    updateDisplayMode();
    m_backgroundCacheDirty = true;
}

void ResponsiveFileItem::updateDisplayMode()
{
    DisplayMode newMode = calculateDisplayMode(width());
    if (newMode != m_currentMode) {
        m_currentMode = newMode;
        m_backgroundCacheDirty = true;

        // 触发重绘，带有微妙的动画效果
        QTimer::singleShot(50, this, [this]() {
            update();
        });
    }
}

SonyIveDesign::DisplayMode ResponsiveFileItem::calculateDisplayMode(int width) const
{
    if (width < 180) return SonyIveDesign::DisplayMode::Micro;
    if (width < 250) return SonyIveDesign::DisplayMode::Compact;
    if (width < 350) return SonyIveDesign::DisplayMode::Standard;
    if (width < 450) return SonyIveDesign::DisplayMode::Expanded;
    return SonyIveDesign::DisplayMode::Full;
}

void ResponsiveFileItem::drawSonyBackground(QPainter& painter)
{
    // Sony风格背景：微妙渐变 + 动态阴影
    QRect bgRect = rect().adjusted(2, 2, -2, -2);

    // 创建渐变背景
    QLinearGradient bgGradient(0, 0, 0, height());

    if (m_isSelected) {
        // 选中状态：蓝色科技感渐变
        bgGradient.setColorAt(0, QColor(0, 123, 255, 200));
        bgGradient.setColorAt(1, QColor(0, 86, 179, 220));

        // 选中时的外发光效果
        painter.setPen(QPen(QColor(0, 123, 255, 100), 2));
    } else if (m_isHovered) {
        // 悬停状态：温暖的灰色渐变
        bgGradient.setColorAt(0, QColor(250, 250, 250, 180));
        bgGradient.setColorAt(1, QColor(240, 240, 240, 200));

        painter.setPen(QPen(QColor(200, 200, 200, 150), 1));
    } else {
        // 默认状态：纯净的白色/透明
        bgGradient.setColorAt(0, QColor(255, 255, 255, 0));
        bgGradient.setColorAt(1, QColor(248, 248, 248, 50));

        painter.setPen(Qt::NoPen);
    }

    painter.setBrush(bgGradient);
    painter.drawRoundedRect(bgRect, BORDER_RADIUS, BORDER_RADIUS);

    // Sony特色：微妙的底部高光
    if (m_isSelected || m_isHovered) {
        QLinearGradient highlight(0, height() - 1, 0, height());
        highlight.setColorAt(0, QColor(255, 255, 255, 0));
        highlight.setColorAt(1, QColor(255, 255, 255, 80));

        painter.setBrush(highlight);
        painter.setPen(Qt::NoPen);

        QPainterPath highlightPath;
        highlightPath.addRoundedRect(bgRect.adjusted(0, height()/2, 0, 0),
                                   BORDER_RADIUS, BORDER_RADIUS);
        painter.drawPath(highlightPath);
    }
}

void ResponsiveFileItem::drawAdaptiveIcon(QPainter& painter)
{
    QRect iconRect = getIconRect();

    // 根据显示模式调整图标大小
    int iconSize;
    switch (m_currentMode) {
        case SonyIveDesign::DisplayMode::Micro:
            iconSize = ICON_SIZE_SMALL;
            break;
        case SonyIveDesign::DisplayMode::Compact:
            iconSize = ICON_SIZE_MEDIUM;
            break;
        default:
            iconSize = ICON_SIZE_LARGE;
            break;
    }

    // 获取文件类型图标 - 使用原有的预设图标系统
    QIcon fileIcon = getStatusIcon();

    // Sony风格：图标带微妙阴影
    if (m_currentMode != SonyIveDesign::DisplayMode::Micro) {
        painter.setOpacity(0.3);
        painter.drawPixmap(iconRect.adjusted(1, 1, 1, 1),
                          fileIcon.pixmap(iconSize, iconSize));
        painter.setOpacity(1.0);
    }

    // 主图标
    painter.drawPixmap(iconRect, fileIcon.pixmap(iconSize, iconSize));
}

void ResponsiveFileItem::drawAdaptiveText(QPainter& painter)
{
    QRect textRect = getTextRect();
    QFont font = getAdaptiveFont();
    painter.setFont(font);

    // 获取自适应文件名
    QString displayName = getAdaptiveFileName(textRect.width(), font);

    // Sony风格文字颜色
    QColor textColor;
    if (m_isSelected) {
        textColor = Qt::white;
    } else {
        textColor = QColor(33, 33, 33); // Sony深灰
    }

    painter.setPen(textColor);

    // 根据显示模式调整文字布局
    switch (m_currentMode) {
        case SonyIveDesign::DisplayMode::Micro: {
            // 极简模式：只显示文件名，垂直居中
            painter.drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, displayName);
            break;
        }

        case SonyIveDesign::DisplayMode::Compact: {
            // 紧凑模式：文件名 + 简单状态
            painter.drawText(textRect.adjusted(0, 0, 0, -15),
                           Qt::AlignLeft | Qt::AlignVCenter, displayName);

            // 状态文字
            QString statusText = m_fileInfo.processStatusToString(m_fileInfo.processStatus);
            QFont smallFont = font;
            smallFont.setPointSize(font.pointSize() - 1);
            painter.setFont(smallFont);
            painter.setPen(m_isSelected ? QColor(200, 200, 200) : QColor(128, 128, 128));
            painter.drawText(textRect.adjusted(0, 15, 0, 0),
                           Qt::AlignLeft | Qt::AlignVCenter, statusText);
            break;
        }

        case SonyIveDesign::DisplayMode::Standard:
        case SonyIveDesign::DisplayMode::Expanded:
        case SonyIveDesign::DisplayMode::Full: {
            // 标准及以上模式：多行信息展示
            painter.drawText(textRect.adjusted(0, 0, 0, -20),
                           Qt::AlignLeft | Qt::AlignVCenter, displayName);

            // 第二行：页码 + 布局模式
            QFont smallFont = font;
            smallFont.setPointSize(font.pointSize() - 1);
            painter.setFont(smallFont);
            painter.setPen(m_isSelected ? QColor(200, 200, 200) : QColor(100, 100, 100));

            QString secondLine;
            if (m_fileInfo.pageCount > 0) {
                secondLine += QString("%1页").arg(m_fileInfo.pageCount);
            }

            if (m_currentMode >= SonyIveDesign::DisplayMode::Expanded) {
                QString layoutText = m_fileInfo.layoutModeToString(m_fileInfo.layoutMode);
                if (!secondLine.isEmpty()) secondLine += " • ";
                secondLine += layoutText;
            }

            if (m_currentMode == SonyIveDesign::DisplayMode::Full && !m_fileInfo.lastModified.isNull()) {
                if (!secondLine.isEmpty()) secondLine += " • ";
                secondLine += m_fileInfo.lastModified.toString("MM/dd");
            }

            painter.drawText(textRect.adjusted(0, 20, 0, 0),
                           Qt::AlignLeft | Qt::AlignVCenter, secondLine);
            break;
        }
    }
}

void ResponsiveFileItem::drawProgressIndicator(QPainter& painter)
{
    // 检查两个状态字段：新的processStatus和旧的status（与CustomFileItem保持一致）
    bool isProcessing = (m_fileInfo.processStatus == FileProcessStatus::Processing ||
                        m_fileInfo.status == FileStatusIconManager::FileStatus::Processing) &&
                       m_fileInfo.progress > 0;

    if (!isProcessing) {
        return;
    }

    QRect progressRect = getProgressRect();

    // Sony风格进度条：圆角 + 渐变
    painter.setRenderHint(QPainter::Antialiasing);

    // 背景轨道
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(200, 200, 200, 100));
    painter.drawRoundedRect(progressRect, 2, 2);

    // 进度填充
    if (m_fileInfo.progress > 0) {
        int progressWidth = (progressRect.width() * m_fileInfo.progress) / 100;
        QRect fillRect = progressRect.adjusted(0, 0, progressWidth - progressRect.width(), 0);

        QLinearGradient progressGradient(0, fillRect.top(), 0, fillRect.bottom());
        progressGradient.setColorAt(0, QColor(0, 123, 255));
        progressGradient.setColorAt(1, QColor(0, 86, 179));

        painter.setBrush(progressGradient);
        painter.drawRoundedRect(fillRect, 2, 2);
    }
}

void ResponsiveFileItem::drawStatusBadge(QPainter& painter)
{
    QRect statusRect = getStatusRect();

    // 根据状态选择颜色
    QColor badgeColor;
    switch (m_fileInfo.processStatus) {
        case FileProcessStatus::Completed:
            badgeColor = QColor(76, 175, 80); // 绿色
            break;
        case FileProcessStatus::Processing:
            badgeColor = QColor(255, 193, 7); // 黄色
            break;
        case FileProcessStatus::Error:
            badgeColor = QColor(244, 67, 54); // 红色
            break;
        default:
            badgeColor = QColor(158, 158, 158); // 灰色
            break;
    }

    // Sony风格状态徽章
    painter.setPen(Qt::NoPen);
    painter.setBrush(badgeColor);
    painter.drawEllipse(statusRect);

    // 内部高光
    painter.setBrush(QColor(255, 255, 255, 60));
    painter.drawEllipse(statusRect.adjusted(1, 1, -1, -1));
}

void ResponsiveFileItem::drawMicroOverlay(QPainter& painter)
{
    // Micro模式的特殊处理：悬停时显示工具提示预览
    if (m_isHovered) {
        QString tooltip = QString("%1\n%2页 • %3")
                         .arg(m_fileInfo.fileName)
                         .arg(m_fileInfo.pageCount)
                         .arg(m_fileInfo.processStatusToString(m_fileInfo.processStatus));

        setToolTip(tooltip);

        // 绘制悬停指示器
        painter.setPen(QPen(QColor(0, 123, 255), 2));
        painter.setBrush(Qt::NoBrush);
        painter.drawRoundedRect(rect().adjusted(1, 1, -1, -1), BORDER_RADIUS, BORDER_RADIUS);
    }
}

QString ResponsiveFileItem::getAdaptiveFileName(int availableWidth, const QFont& font) const
{
    QString fileName = m_fileInfo.fileName;

    // 移除文件扩展名以节省空间（除了Micro模式）
    if (m_currentMode != SonyIveDesign::DisplayMode::Micro && m_currentMode != SonyIveDesign::DisplayMode::Full) {
        QFileInfo fileInfo(fileName);
        fileName = fileInfo.baseName();
    }

    return getSmartEllipsis(fileName, availableWidth, font);
}

QString ResponsiveFileItem::getSmartEllipsis(const QString& text, int maxWidth, const QFont& font) const
{
    QFontMetrics fm(font);

    if (fm.horizontalAdvance(text) <= maxWidth) {
        return text;
    }

    // 智能省略：保留文件名开头和结尾的重要部分
    QString ellipsis = "...";
    int ellipsisWidth = fm.horizontalAdvance(ellipsis);
    int availableWidth = maxWidth - ellipsisWidth;

    if (availableWidth <= 0) {
        return ellipsis;
    }

    // 分配2/3给开头，1/3给结尾
    int frontWidth = availableWidth * 2 / 3;
    int backWidth = availableWidth / 3;

    QString front, back;
    for (int i = 0; i < text.length(); i++) {
        if (fm.horizontalAdvance(text.left(i + 1)) <= frontWidth) {
            front = text.left(i + 1);
        } else {
            break;
        }
    }

    for (int i = text.length() - 1; i >= 0; i--) {
        if (fm.horizontalAdvance(text.mid(i)) <= backWidth) {
            back = text.mid(i);
            break;
        }
    }

    return front + ellipsis + back;
}

QFont ResponsiveFileItem::getAdaptiveFont() const
{
    QFont font = this->font();

    // 根据显示模式调整字体大小
    switch (m_currentMode) {
        case SonyIveDesign::DisplayMode::Micro:
            font.setPointSize(qMax(8, font.pointSize() - 3));
            break;
        case SonyIveDesign::DisplayMode::Compact:
            font.setPointSize(qMax(9, font.pointSize() - 2));
            break;
        case SonyIveDesign::DisplayMode::Standard:
            font.setPointSize(qMax(10, font.pointSize() - 1));
            break;
        default:
            // 保持默认大小
            break;
    }

    return font;
}

QRect ResponsiveFileItem::getIconRect() const
{
    int iconSize;
    int margin;

    switch (m_currentMode) {
        case SonyIveDesign::DisplayMode::Micro:
            iconSize = ICON_SIZE_SMALL;
            margin = MARGIN_SMALL;
            break;
        case SonyIveDesign::DisplayMode::Compact:
            iconSize = ICON_SIZE_MEDIUM;
            margin = MARGIN_MEDIUM;
            break;
        default:
            iconSize = ICON_SIZE_LARGE;
            margin = MARGIN_LARGE;
            break;
    }

    int y = (height() - iconSize) / 2;
    return QRect(margin, y, iconSize, iconSize);
}

QRect ResponsiveFileItem::getTextRect() const
{
    QRect iconRect = getIconRect();
    int leftMargin = iconRect.right() + MARGIN_MEDIUM;
    int rightMargin = MARGIN_LARGE;

    // 为状态徽章预留空间
    if (m_currentMode >= SonyIveDesign::DisplayMode::Compact) {
        rightMargin += 20;
    }

    return QRect(leftMargin, 0, width() - leftMargin - rightMargin, height());
}

QRect ResponsiveFileItem::getProgressRect() const
{
    QRect textRect = getTextRect();
    int progressHeight = 3;
    int y = height() - MARGIN_SMALL - progressHeight;

    return QRect(textRect.left(), y, textRect.width(), progressHeight);
}

QRect ResponsiveFileItem::getStatusRect() const
{
    int badgeSize = 8;
    int margin = MARGIN_MEDIUM;
    int x = width() - margin - badgeSize;
    int y = (height() - badgeSize) / 2;

    return QRect(x, y, badgeSize, badgeSize);
}

void ResponsiveFileItem::animateSelection(bool selected)
{
    m_selectionAnimation->stop();
    m_selectionAnimation->setStartValue(selected ? 0.7 : 1.0);
    m_selectionAnimation->setEndValue(selected ? 1.0 : 0.7);
    m_selectionAnimation->start();
}

void ResponsiveFileItem::animateHover(bool hovered)
{
    m_hoverAnimation->stop();
    m_hoverAnimation->setStartValue(hovered ? 1.0 : 1.1);
    m_hoverAnimation->setEndValue(hovered ? 1.05 : 1.0);
    m_hoverAnimation->start();
}

// 鼠标事件处理（保持与原CustomFileItem兼容）
void ResponsiveFileItem::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        m_isDragStarted = false;
        m_dragStartPos = event->pos();
        emit clicked(this, event->modifiers());
    } else if (event->button() == Qt::RightButton) {
        emit rightClicked(this, event->globalPosition().toPoint());
    }
}

void ResponsiveFileItem::mouseDoubleClickEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        emit doubleClicked(this);
    }
}

void ResponsiveFileItem::mouseMoveEvent(QMouseEvent* event)
{
    if ((event->buttons() & Qt::LeftButton) && !m_isDragStarted) {
        int dragDistance = (event->pos() - m_dragStartPos).manhattanLength();
        if (dragDistance >= QApplication::startDragDistance()) {
            m_isDragStarted = true;
            emit dragStartRequested(this, m_dragStartPos);
        }
    }
}

void ResponsiveFileItem::enterEvent(QEnterEvent* event)
{
    Q_UNUSED(event)
    setHovered(true);
}

void ResponsiveFileItem::leaveEvent(QEvent* event)
{
    Q_UNUSED(event)
    setHovered(false);
}

QIcon ResponsiveFileItem::getStatusIcon() const
{
    // 使用与CustomFileItem相同的图标获取逻辑
    QString ext = QFileInfo(m_fileInfo.filePath).suffix().toLower();
    if (ext == "pdf") return QIcon(":/icons/pdf_file.png");
    if (ext == "png") return QIcon(":/icons/png_file.png");
    if (ext == "jpg") return QIcon(":/icons/jpg_file.png");
    if (ext == "jpeg") return QIcon(":/icons/jpeg_file.png");
    if (ext == "bmp" || ext == "gif" || ext == "tiff" || ext == "webp") return QIcon(":/icons/image_file.png");

    QString type = UnifiedFileInfo::fileTypeToString(m_fileInfo.fileType).toLower();
    if (type == "pdf") return QIcon(":/icons/pdf_file.png");
    if (type == "png") return QIcon(":/icons/png_file.png");
    if (type == "jpg") return QIcon(":/icons/jpg_file.png");
    if (type == "jpeg") return QIcon(":/icons/jpeg_file.png");
    if (type == "image" || type == "bmp" || type == "gif" || type == "tiff" || type == "webp")
        return QIcon(":/icons/image_file.png");

    // 默认图标
    return QIcon(":/icons/unknown_file.png");
}